/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-10-18     Meco Man     The first version
 * 2021-12-17     Wayne        Add input event
 */
#include <lvgl.h>
#include <rtdevice.h>
#include <stdbool.h>
#include "stm32h745i_discovery_ts.h"

static void input_read(lv_indev_drv_t* indev_drv, lv_indev_data_t* data)
{
    TS_State_t state = {0};
    int status = BSP_TS_GetState(0, &state);
    if (status != BSP_ERROR_NONE) {
        rt_kprintf("%s: BSP_TS_GetState failed!\n", __func__);
    }

    data->state = state.TouchDetected ? LV_INDEV_STATE_PRESSED : LV_INDEV_STATE_RELEASED;
    data->point.x = state.TouchX;
    data->point.y = state.TouchY;
}

void lv_port_indev_init(void)
{
    static lv_indev_drv_t indev_drv;

    TS_Init_t ts_init = {0};
    ts_init.Width = TS_MAX_WIDTH;
    ts_init.Height = TS_MAX_HEIGHT;
    ts_init.Orientation = TS_SWAP_XY;
    ts_init.Accuracy = 1;

    int32_t status = 0;
    status = BSP_TS_Init(0, &ts_init);
    if (status != BSP_ERROR_NONE) {
        rt_kprintf("%s: BSP_TS_Init failed!\n", __func__);
        return;
    }
    rt_kprintf("BSP_TS_Init OK!\n");

    /* Basic initialization */
    lv_indev_drv_init(&indev_drv);
    indev_drv.type = LV_INDEV_TYPE_POINTER;
    indev_drv.read_cb = input_read;

    /* Register the driver in LVGL and save the created input device object */
    lv_indev_drv_register(&indev_drv);
}
